﻿// This code is released under the BSD license.
namespace PugLib.Drawing
{
    using System.Drawing;
    using System.Drawing.Imaging;

    public static class GrayscaleImage
    {
        /// <summary>
        /// Returns a grayscale copy of the supplied image.
        /// </summary>
        /// <param name="image"></param>
        /// <returns></returns>
        public static Image ApplyGrayscale(Image image)
        {
            Image copy = image.Clone() as Image;
            // Build color matrix set at 1/3
            ColorMatrix matrix = new ColorMatrix();
            const float scale = 1 / 3f;
            matrix[0, 0] = scale;
            matrix[0, 1] = scale;
            matrix[0, 2] = scale;
            matrix[1, 0] = scale;
            matrix[1, 1] = scale;
            matrix[1, 2] = scale;
            matrix[2, 0] = scale;
            matrix[2, 1] = scale;
            matrix[2, 2] = scale;

            // Create image attributes that will applied to the image
            ImageAttributes attributes = new ImageAttributes();
            attributes.SetColorMatrix(matrix);

            // Get the graphics object from the image
            if (copy != null)
            {
                using (Graphics g = Graphics.FromImage(copy))
                {
                    // Redraw the image on the graphics object using the grayscale color matrix
                    g.DrawImage(image,
                                new Rectangle(0, 0, copy.Width, copy.Height),
                                0,
                                0,
                                copy.Width,
                                copy.Height,
                                GraphicsUnit.Pixel,
                                attributes);
                }
            }
            return copy;
        }
    }
}